package org.lanyu.springainovel.chat.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.lanyu.springainovel.common.entity.ChatSessionHistory;
import org.lanyu.springainovel.common.entity.SpringAIChatMemory;
import org.lanyu.springainovel.chat.mapper.ChatMemoryMapper;
import org.lanyu.springainovel.chat.mapper.ChatSessionHistoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatSessionHistoryService {
    @Autowired
    private ChatSessionHistoryMapper historyMapper;

    @Autowired
    private ChatMemoryMapper chatMemoryRepository;

    public ChatSessionHistoryService() { super(); }

    public ChatSessionHistory createSession(ChatSessionHistory session) {
        historyMapper.insert(session);
        return session;
    }

    public List<ChatSessionHistory> getSessionsByUser(Long userId) {
        return historyMapper.selectList(
            new QueryWrapper<ChatSessionHistory>().eq("user_id", userId).eq("status", 1).orderByDesc("update_time")
        );
    }

    public ChatSessionHistory getSessionById(String sessionId) {
        return historyMapper.selectById(sessionId);
    }

    /**
     * 根据会话ID获取会话记录
     * 
     * @param sessionId 会话ID
     * @return 会话记录
     */
    public ChatSessionHistory getSessionBySessionId(String sessionId) {
        return historyMapper.selectOne(
            new QueryWrapper<ChatSessionHistory>().eq("session_id", sessionId).eq("status", 1)
        );
    }

    public ChatSessionHistory updateSession(ChatSessionHistory session) {
        historyMapper.updateById(session);
        return session;
    }

    /**
     * 删除会话
     */
    public void deleteSessionHistory(String sessionId) {
        historyMapper.delete(new QueryWrapper<ChatSessionHistory>().eq("session_id", sessionId));
    }

    /**
     * 更新会话标题
     * 
     * @param sessionId 会话ID
     * @param title 新标�?     */
    public void updateSessionTitle(String sessionId, String title) {
        ChatSessionHistory session = getSessionBySessionId(sessionId);
        if (session != null) {
            session.setTitle(title);
            historyMapper.updateById(session);
        }
    }

    /**
     * 删除用户的所有会�?     * @param userId 用户ID
     */
    public void deleteAllSessionsByUser(Long userId) {
        // 直接软删除用户的所有会�?
        ChatSessionHistory updateSession = new ChatSessionHistory();
        updateSession.setStatus(0); // 软删�?        
        historyMapper.update(updateSession,
            new QueryWrapper<ChatSessionHistory>()
                .eq("user_id", userId)
                .eq("status", 1)
        );
        
        // 获取用户的所有会话ID，用于删除聊天记�?
        List<ChatSessionHistory> sessions = historyMapper.selectList(
            new QueryWrapper<ChatSessionHistory>()
                .select("session_id")
                .eq("user_id", userId)
        );
        
        // 删除所有相关的聊天记录
        if (!sessions.isEmpty()) {
            List<String> sessionIds = sessions.stream()
                .map(ChatSessionHistory::getSessionId)
                .collect(java.util.stream.Collectors.toList());
                
            chatMemoryRepository.delete(
                new QueryWrapper<SpringAIChatMemory>()
                    .in("conversation_id", sessionIds)
            );
        }
    }

    public ChatMemoryMapper getChatMemoryRepository() {
        return chatMemoryRepository;
    }
}
